//! gRPC API实现

use std::sync::Arc;
use tracing::info;

use nacos_core::traits::{NamingService, ConfigService};
use nacos_network::grpc::service::{ClusterService, DataSyncService};

/// gRPC API服务器
pub struct GrpcApiServer {
    config: super::ApiConfig,
    naming_service: Arc<dyn NamingService>,
    config_service: Arc<dyn ConfigService>,
    cluster_service: Arc<dyn ClusterService>,
    data_sync_service: Arc<dyn DataSyncService>,
}

impl GrpcApiServer {
    pub fn new(
        config: super::ApiConfig,
        naming_service: Arc<dyn NamingService>,
        config_service: Arc<dyn ConfigService>,
        cluster_service: Arc<dyn ClusterService>,
        data_sync_service: Arc<dyn DataSyncService>,
    ) -> Self {
        Self {
            config,
            naming_service,
            config_service,
            cluster_service,
            data_sync_service,
        }
    }

    pub async fn start(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let addr = format!("0.0.0.0:{}", self.config.grpc_port).parse()?;
        info!("启动gRPC API服务器: {}", addr);

        // 使用nacos-network中的NacosGrpcService
        let grpc_service = nacos_network::grpc::service::NacosGrpcService::new(
            self.cluster_service.clone(),
            self.data_sync_service.clone(),
        );

        let server = nacos_network::proto::nacos_service_server::NacosServiceServer::new(grpc_service);

        tonic::transport::Server::builder()
            .add_service(server)
            .serve(addr)
            .await?;

        Ok(())
    }

    pub async fn stop(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        info!("停止gRPC API服务器");
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use nacos_core::MockNamingService;
    use nacos_core::MockConfigService;

    #[tokio::test]
    async fn test_grpc_api_server() {
        let config = super::super::ApiConfig::default();
        let naming_service = Arc::new(MockNamingService::new());
        let config_service = Arc::new(MockConfigService::new());
        let cluster_service = Arc::new(crate::cluster_adapter::ServerClusterService::new(
            nacos_cluster::ClusterManager::new(nacos_cluster::ClusterConfig::default()).into(),
        ));
        let data_sync_service = Arc::new(crate::cluster_adapter::ServerDataSyncService::new(
            nacos_cluster::DataSyncManager::new(
                nacos_cluster::ClusterManager::new(nacos_cluster::ClusterConfig::default()).into(),
            ).into(),
        ));

        let server = GrpcApiServer::new(
            config,
            naming_service,
            config_service,
            cluster_service,
            data_sync_service,
        );

        // 测试创建成功
        assert_eq!(server.config.grpc_port, 9090);
    }
}